// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'

const EMPTY = { visible: false, obj: null, close: null, change: null }

// ============================== 导出混入 ============================== //

export default (components) => {
  const NAME = Object.keys(components)

  return {
    /**
     * 名称定义 (实际使用名称)
     */
    name: 'WindowAdd',

    /**
     * 组件导入 (Abc.vue + Abc/index.vue)
     */
    components,

    /**
     * 状态数据 (函数返回对象)
     */
    data() {
      return {
        add: NAME.reduce((obj, name) => ({ ...obj, [name]: CORE.clone(EMPTY) }), {}),
      }
    },

    /**
     * 创建完成 (先抽取再调用)
     */
    created() {
      NAME.forEach((name) => {
        const method = CORE.keyPre(name, 'open')

        this.$set(CORE.WATCH, name, false) // 全局的新增监听

        this.$set(CORE.WATCH, name.replace(/^Add/, 'Edit'), false) // 全局的修改监听

        window[method] = CORE[method] = async (data, close, change) => {
          const obj = CORE.isEvent(data) || !CORE.isJSON(data) ? null : data
          Object.assign(this.add[name], { visible: true, obj, close, change }) // 浅覆盖
        }
      })
    },

    /**
     * 本地方法 (轻量重要在前)
     */
    methods: {
      /**
       * 关闭
       */
      toClose(name) {
        const { close } = this.add[name]
        CORE.isFunction(close) && close()

        Object.assign(this.add[name], CORE.clone(EMPTY))
      },

      /**
       * 更新
       */
      async toChange(name) {
        const { change, obj } = this.add[name]
        CORE.isFunction(change) && change()

        const watchName = obj && obj.id ? name.replace(/^Add/, 'Edit') : name // 有 id 即为修改

        CORE.WATCH[watchName] = true
        await this.$nextTick()
        CORE.WATCH[watchName] = false
      },
    },
  }
}
